package com.boot.conf;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageHelper;


@Configuration
@MapperScan(basePackages = {MysqlDataSourceConfig.PACKAGE1}, sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class MysqlDataSourceConfig {
	private final Logger logger = LoggerFactory.getLogger(getClass());
//	static final String PACKAGE2 = "com.boot.dao";
	static final String PACKAGE1 = "com.boot.dao";
//	@Value("${datasource_mysql_driverClassName}")
	@Value("${spring.datasource.driverClassName}")
	private String driverClassName;
//	@Value("${datasource_mysql_url}")
	@Value("${spring.datasource.url}")
	private String dbUrl;
	@Value("${spring.datasource.username}")
	private String dbUser;
//	@Value("${datasource_mysql_password}")
	@Value("${spring.datasource.password}")
	private String dbPassword;

	@Bean(name = "mysqlDataSource")
	@Primary
	public DataSource mysqlDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDbType("mysql");
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(dbUrl);
		dataSource.setUsername(dbUser);
		dataSource.setPassword(dbPassword);
		try {
			dataSource.setFilters("stat, wall");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dataSource;
	}

	@Bean(name = "mysqlSqlSessionFactory")
	@Primary
	public SqlSessionFactory mysqlSqlSessionFactory() {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(mysqlDataSource());
		bean.setTypeAliasesPackage("com.boot.entity");

		// 分页插件
		PageHelper pageHelper = new PageHelper();
		Properties properties = new Properties();
		properties.setProperty("reasonable", "true");
		properties.setProperty("supportMethodsArguments", "true");
		properties.setProperty("returnPageInfo", "check");
		properties.setProperty("params", "count=countSql");
		properties.setProperty("dialect", "mysql");
		pageHelper.setProperties(properties);
		bean.setPlugins(new Interceptor[] { pageHelper });

		// 添加mybatis配置文件
		PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
		try {
			bean.setMapperLocations(resourceResolver.getResources("classpath*:mapper/mysql/*.xml"));
//			bean.setMapperLocations(resourceResolver.getResources("com.boot.mapper.*.xml"));
			SqlSessionFactory sqlSessionFactory = bean.getObject();
			org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
			// 设置支持字段对应实体属性驼峰格式
			configuration.setMapUnderscoreToCamelCase(true);

			return bean.getObject();
		} catch (IOException e) {
			logger.error("获取mapper资源出现异常", e);
			throw new RuntimeException("获取mapper资源出现异常", e);
		} catch (Exception e) {
			logger.error("初始化sqlSessionFactory时出现异常", e);
			throw new RuntimeException("初始化sqlSessionFactory时出现异常", e);
		}
	}

	/**
	 * 因为当前项目中有
	 * 
	 * @return
	 */
	@Bean(name = "mysqlTransactionManager")
	@Primary
	public DataSourceTransactionManager mysqlTransactionManager() {
		DataSourceTransactionManager manager = new DataSourceTransactionManager(mysqlDataSource());
		return manager;
	}
}